﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using DeepZoomPivotConstructor.DTBuilderLib;

namespace DeepZoomPivotConstructor.BinaryIO
{
    /// <summary>
    /// Coordinates reading and writing the layout file.
    /// Returns things in a XML format for pleasure and joy.
    /// </summary>
    public class LayoutFileIO
    {
        /// <summary>
        /// Returns the layout collection after reading it from a binary file.
        /// </summary>
        /// <param name="inputFile"></param>
        /// <returns></returns>
        public static LayoutCollection Load(FileInfo inputFile)
        {
            using (BinaryReader br = new BinaryReader(inputFile.OpenRead()))
            {
                LayoutCollection result = new LayoutCollection();

                result.ItemCount = br.ReadInt32();
                List<LayoutItemInfo> items = new List<LayoutItemInfo>();
                for (int i = 0; i < result.ItemCount; i++)
                {
                    LayoutItemInfo info = new LayoutItemInfo();
                    info.ID = br.ReadInt32();
                    info.X = br.ReadSingle();
                    info.Y = br.ReadSingle();
                    info.Width = br.ReadSingle();
                    items.Add(info);
                }

                result.Item = items.ToArray();
                br.Close();
                return result;
            }
        }

        /// <summary>
        /// Save the binary layout collection to a new file.
        /// </summary>
        /// <param name="c"></param>
        /// <param name="output"></param>
        public static void Save(LayoutCollection c, FileInfo output)
        {
            using (BinaryWriter wr = new BinaryWriter(output.Create()))
            {
                wr.Write((int)c.ItemCount);

                foreach (var item in c.Item)
                {
                    wr.Write((int)item.ID);
                    wr.Write((float)item.X);
                    wr.Write((float)item.Y);
                    wr.Write((float)item.Width);
                }
                wr.Close();
            }
        }
    }
}
